<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Lambda编程-kotlin基础(四) | Hexo</title><meta name="keywords" content="kotlin基础,Java函数式API,kotlin集合"><meta name="author" content="Joey"><meta name="copyright" content="Joey"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Lambda编程一、集合的创建，遍历传统意义上的集合： List &#x2F;Set ， Map也算。 （在java中它们都是接口）  List 主要实现类是 ArrayList、LinkedList   Set  主要实现类是 HashSet  Map 主要实现类 HashMap    示例：包含水果的集合 12345&#x2F;&#x2F;add 法val list &#x3D; ArrayList&lt;String&gt;()l">
<meta property="og:type" content="article">
<meta property="og:title" content="Lambda编程-kotlin基础(四)">
<meta property="og:url" content="https://jonhsean.gitee.io/blog/2022/10/14/daily/kotlin_lambda%E7%BC%96%E7%A8%8B/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="Lambda编程一、集合的创建，遍历传统意义上的集合： List &#x2F;Set ， Map也算。 （在java中它们都是接口）  List 主要实现类是 ArrayList、LinkedList   Set  主要实现类是 HashSet  Map 主要实现类 HashMap    示例：包含水果的集合 12345&#x2F;&#x2F;add 法val list &#x3D; ArrayList&lt;String&gt;()l">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg">
<meta property="article:published_time" content="2022-10-14T07:23:56.000Z">
<meta property="article:modified_time" content="2022-10-14T14:01:12.662Z">
<meta property="article:author" content="Joey">
<meta property="article:tag" content="kotlin基础">
<meta property="article:tag" content="Java函数式API">
<meta property="article:tag" content="kotlin集合">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://jonhsean.gitee.io/blog/2022/10/14/daily/kotlin_lambda%E7%BC%96%E7%A8%8B/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://unpkg.com/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://unpkg.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"/blog/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":100,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: {"limitDay":180,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://unpkg.com/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://unpkg.com/flickr-justified-gallery/dist/fjGallery.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Lambda编程-kotlin基础(四)',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-14 22:01:12'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">21</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">30</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">Hexo</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">Lambda编程-kotlin基础(四)</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-10-14T07:23:56.000Z" title="发表于 2022-10-14 15:23:56">2022-10-14</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-10-14T14:01:12.662Z" title="更新于 2022-10-14 22:01:12">2022-10-14</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/kotlin/">kotlin</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/kotlin/Lambda/">Lambda</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E7%AC%AC%E4%B8%80%E8%A1%8C%E4%BB%A3%E7%A0%81/">第一行代码</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E7%AC%AC%E4%B8%80%E8%A1%8C%E4%BB%A3%E7%A0%81/kotlin/">kotlin</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Lambda编程-kotlin基础(四)"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="Lambda编程"><a href="#Lambda编程" class="headerlink" title="Lambda编程"></a>Lambda编程</h1><h2 id="一、集合的创建，遍历"><a href="#一、集合的创建，遍历" class="headerlink" title="一、集合的创建，遍历"></a>一、集合的创建，遍历</h2><p>传统意义上的集合： <code>List</code> /<code>Set</code> ， <code>Map</code>也算。 （在<code>java</code>中它们都是接口）</p>
<ul>
<li><p><code>List</code> 主要实现类是 <code>ArrayList</code>、<code>LinkedList</code> </p>
</li>
<li><p><code>Set</code>  主要实现类是 <code>HashSet</code></p>
</li>
<li><p><code>Map</code> 主要实现类 <code>HashMap</code> </p>
</li>
</ul>
<p>示例：包含水果的集合</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//add 法</span></span><br><span class="line"><span class="keyword">val</span> list = ArrayList&lt;String&gt;()</span><br><span class="line">list.add(<span class="string">&quot;Apple&quot;</span>)</span><br><span class="line">list.add(<span class="string">&quot;Banana&quot;</span>)</span><br><span class="line">...一直add下去...</span><br></pre></td></tr></table></figure>



<hr>
<h3 id="1-List"><a href="#1-List" class="headerlink" title="1. List"></a>1. List</h3><p><code>Kotlin</code>中内置 <code>listOf()</code> 函数来简化初始化集合的写法</p>
<ul>
<li>其创建的是一个<strong>不可变</strong>的集合：即只能读取，不能删除修改添加。</li>
</ul>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">val</span> list = listOf(<span class="string">&quot;Apple&quot;</span>,<span class="string">&quot;Banana&quot;</span>,...) <span class="comment">//...中写入子元素</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">//遍历集合</span></span><br><span class="line">    <span class="keyword">for</span> (fruit <span class="keyword">in</span> list)&#123;</span><br><span class="line">        println(fruit)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>创建<strong>可变集合</strong>： <code>mutableListOf()</code></li>
</ul>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//添加一个元素</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">val</span> list = mutableListOf(<span class="string">&quot;Apple&quot;</span>,<span class="string">&quot;Banana&quot;</span>,...) <span class="comment">//...中写入子元素</span></span><br><span class="line">    list.add(<span class="string">&quot;Orange&quot;</span>) <span class="comment">// ➕</span></span><br><span class="line">    <span class="comment">//遍历集合</span></span><br><span class="line">    <span class="keyword">for</span> (fruit <span class="keyword">in</span> list)&#123;</span><br><span class="line">        println(fruit)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h3 id="2-Set"><a href="#2-Set" class="headerlink" title="2. Set"></a>2. Set</h3><blockquote>
<p><code>Set</code> 集合 ： 创建为 <code>setOf()</code> 和  <code>mutableSetOf()</code></p>
<ul>
<li>注意： <code>Set</code> 集合中不可以存放重复元素，若存放多个相同元素，只会保留一个</li>
<li>上面就是与 <code>List</code>集合最大的不同之处</li>
</ul>
<p><code>Map</code> 集合 ： 创建为 <code>mapOf()</code> 和  <code>mutableMapOf()</code></p>
</blockquote>
<hr>
<h3 id="3-Map-键值对形式"><a href="#3-Map-键值对形式" class="headerlink" title="3. Map 键值对形式"></a>3. Map 键值对形式</h3><p>传统<code>Map</code> 是先创建一个<code>HashMap</code>实例，然后将一个个键值对数据添加到<code>Map</code>中</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> map = HashMap&lt;String, <span class="built_in">Int</span>&gt;()</span><br><span class="line">map.put(<span class="string">&quot;Apple&quot;</span>,<span class="number">1</span>)</span><br><span class="line">map.put(<span class="string">&quot;Banana&quot;</span>,<span class="number">2</span>)</span><br><span class="line">...put下去..</span><br><span class="line"><span class="comment">//kotlin 不建议用 put 和 get 来操作Map ; 推荐使用数据下标的方式。</span></span><br></pre></td></tr></table></figure>

<hr>
<h4 id="1-操作方式"><a href="#1-操作方式" class="headerlink" title="1. 操作方式"></a>1. 操作方式</h4><ul>
<li><p>添加： <code>map[&quot;Apple&quot;]=1</code>  //操作对象似的</p>
</li>
<li><p>读取： <code>val number = map[&quot;Apple&quot;]</code>  //操作对象似的</p>
</li>
</ul>
<h4 id="2-创建并使用"><a href="#2-创建并使用" class="headerlink" title="2. 创建并使用"></a>2. 创建并使用</h4><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> map = mapOf(<span class="string">&quot;Apple&quot;</span> to <span class="number">1</span> , <span class="string">&quot;Banana&quot;</span> to <span class="number">2</span>)</span><br><span class="line"><span class="comment">//to 不是关键字，是一个 infix 函数。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//遍历：</span></span><br><span class="line"><span class="keyword">for</span> ((fruit,number) <span class="keyword">in</span> map)&#123;</span><br><span class="line">    println(<span class="string">&quot;fruit is&quot;</span> +fruit+ <span class="string">&quot;,number is &quot;</span> + number)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h2 id="二、集合的函数式API"><a href="#二、集合的函数式API" class="headerlink" title="二、集合的函数式API"></a>二、集合的函数式API</h2><h3 id="1-引子"><a href="#1-引子" class="headerlink" title="1. 引子"></a>1. 引子</h3><p>示例： 找水果集合里单词最长的水果</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> list = listOf(<span class="string">&quot;Apple&quot;</span>,<span class="string">&quot;Banana&quot;</span>)</span><br><span class="line"><span class="keyword">var</span> maxFruit = <span class="string">&quot;&quot;</span></span><br><span class="line"><span class="keyword">for</span> (fruit <span class="keyword">in</span> list)&#123;</span><br><span class="line">    <span class="keyword">if</span>(fruit.length &gt; maxFruit.length)&#123;</span><br><span class="line">        maxFruit = fruit</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">printlin(<span class="string">&quot;max is <span class="variable">$maxFruit</span>&quot;</span>)</span><br></pre></td></tr></table></figure>



<h4 id="简写进化史："><a href="#简写进化史：" class="headerlink" title="简写进化史："></a><strong>简写进化史</strong>：</h4><figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">val</span> list = listOf(<span class="string">&quot;Apple&quot;</span>,<span class="string">&quot;Banana&quot;</span>)</span><br><span class="line"><span class="keyword">val</span> maxFruit = list.maxBy &#123;it.length&#125; <span class="comment">//使用API</span></span><br><span class="line">printlin(<span class="string">&quot;max is <span class="variable">$maxFruit</span>&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//maxBy 函数 接收一个 Lambda 类型的参数，并在遍历集合时将每次遍历的值作为参数传递给Lambda 表达式。</span></span><br><span class="line"><span class="comment">//maxBy 函数工作原理： 根据我们传入的条件来遍历集合</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//相当于： 第一版： </span></span><br><span class="line"><span class="keyword">val</span> lambda = &#123;fruit: String -&gt; fruit.length&#125;</span><br><span class="line"><span class="keyword">val</span> maxFruit = list.maxBy(lambda)</span><br><span class="line"></span><br><span class="line"><span class="comment">//第二版：不需要 lambda 这个变量</span></span><br><span class="line"><span class="keyword">val</span> maxFruit = list.maxBy(&#123;fruit: String -&gt; fruit.length&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">//第三版：kotlin规定，参数原因-移到括号外</span></span><br><span class="line"><span class="keyword">val</span> maxFruit = list.maxBy()&#123;fruit: String -&gt; fruit.length&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//第四版：唯一参数，可省括号</span></span><br><span class="line"><span class="keyword">val</span> maxFruit = list.maxBy&#123;fruit: String -&gt; fruit.length&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//第五版：参数类型可自推</span></span><br><span class="line"><span class="keyword">val</span> maxFruit = list.maxBy&#123;fruit -&gt; fruit.length&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//第六版：参数列表只有一个参数，不必声明；it替代</span></span><br><span class="line"><span class="keyword">val</span> maxFruit = list.maxBy&#123;it -&gt; it.length&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-Lambda"><a href="#2-Lambda" class="headerlink" title="2. Lambda"></a>2. Lambda</h3><p><code>Lambda</code> ： 就是一小段可以<strong>作为参数传递</strong>的<strong>代码</strong></p>
<p>函数式的语法结构（即 <code>Lambda</code>表达式的语法结构）</p>
<blockquote>
<p><code>&#123;参数名1： 参数类型, 参数名2：参数类型 -&gt; 函数体 &#125;</code></p>
<h4 id="特点："><a href="#特点：" class="headerlink" title="特点："></a>特点：</h4><ul>
<li><ol>
<li><strong>函数体</strong> 的<strong>最后一行代码</strong> 会自动作为 <code>Lambda</code>表达式的<strong>返回值</strong></li>
</ol>
</li>
<li><ol start="2">
<li>当 <code>Lambda</code>参数是函数的最后一个参数时，可以将表达式移到函数括号外。(见第三版示例)</li>
<li>接下来，若参数是函数的唯一一个参数时，可以将函数的<strong>括号省略</strong></li>
<li>由于类型推导，参数列表大多情况<strong>不需声明参数类型</strong></li>
<li>当表达式参数列表只有一个参数时，<strong>不必声明参数名</strong>，而用 <code>it</code> 关键字替代</li>
</ol>
</li>
<li><p>结构： 表达式被<strong>大括号</strong>包裹，若有参数传入 则需要<strong>声明</strong>参数列表。</p>
</li>
<li><p><code>-&gt;</code>  表示参数列表的结束 &amp; 函数体的开始</p>
</li>
</ul>
</blockquote>
<h3 id="3-常用4个api"><a href="#3-常用4个api" class="headerlink" title="3. 常用4个api"></a>3. 常用4个api</h3><ul>
<li><code>map()</code> : 用于将集合中的每个元素都映射成一个另外的值，映射的规则在 <code>Lambda</code>表达式中指定,最终生成一个新的集合。</li>
</ul>
<p><strong>示例：</strong>水果名都大写</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">val</span> list = listOf(<span class="string">&quot;Apple&quot;</span>,<span class="string">&quot;Banana&quot;</span>)</span><br><span class="line">    <span class="keyword">val</span> newList = list.map &#123; it.toUpperCase() &#125;</span><br><span class="line">    <span class="keyword">for</span>(fruit <span class="keyword">in</span> newList)&#123;</span><br><span class="line">        println(fruit)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ul>
<li><p><code>filter()</code> 过滤集合中的数据</p>
<p><strong>示例：</strong> 保留5个字母内的水果</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">val</span> list = listOf(<span class="string">&quot;Apple&quot;</span>,<span class="string">&quot;Banana&quot;</span>)</span><br><span class="line">    <span class="keyword">val</span> newList = list.filter &#123; it.length&lt;=<span class="number">5</span> &#125;</span><br><span class="line">    				.map &#123;it.toUpperCase()&#125; <span class="comment">//可以结合起来用，边大写</span></span><br><span class="line">    <span class="keyword">for</span>(fruit <span class="keyword">in</span> newList)&#123;</span><br><span class="line">        println(fruit)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p><code>any()</code> : 用于判断集合中是否至少存在一个元素满足指定条件</p>
</li>
<li><p><code>all()</code>: 用于判断集合中是否所有的元素都满足指定条件</p>
</li>
</ul>
<p><strong>示例：</strong>是否存在5个字母以内的集合，集合是否都是5个字母以内</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">val</span> list = listOf(<span class="string">&quot;Apple&quot;</span>,<span class="string">&quot;Banana&quot;</span>)</span><br><span class="line">    <span class="keyword">val</span> allResult = list.all &#123; it.length&lt;=<span class="number">5</span> &#125;</span><br><span class="line">    <span class="keyword">val</span> anyResult = list.any &#123; it.length&lt;=<span class="number">5</span> &#125;</span><br><span class="line">    println(<span class="string">&quot;anyResult is <span class="variable">$anyResult</span>, allResult is <span class="variable">$allResult</span>&quot;</span>)</span><br><span class="line">    <span class="comment">//true, false</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<hr>
<h2 id="三、Java函数式API的使用"><a href="#三、Java函数式API的使用" class="headerlink" title="三、Java函数式API的使用"></a>三、Java函数式API的使用</h2><h3 id="1-是什么"><a href="#1-是什么" class="headerlink" title="1.是什么"></a>1.是什么</h3><p>即：<code>调用Java方法</code>使用<code>函数式API</code></p>
<h3 id="2-怎么用"><a href="#2-怎么用" class="headerlink" title="2.怎么用"></a>2.怎么用</h3><p>什么时候可以用： <code>Kotlin</code>中调用一个<code>Java</code>方法，并该方法接收一个<code>Java</code><strong>单抽象方法接口</strong>参数。</p>
<blockquote>
<p><strong>单抽象方法接口</strong>:  即接口中<strong>只有一个待实现</strong>的方法。</p>
</blockquote>
<p><strong>示例：</strong></p>
<p>​    Java原生API中最常见的单抽象方法接口：<code>Runnable接口</code>，只有一个待实现的 <code>run()</code>方法。其定义为：<code>public interface Runnable&#123; void run(); &#125;</code></p>
<p>​    该接口主要结合线程使用</p>
<blockquote>
<p><code>Thread</code>类的构造方法接收一个<code>Runnable</code>参数，创建并执行一个子线程如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="title class_">Thread</span>(<span class="keyword">new</span> <span class="title class_">Runnable</span>()&#123; <span class="comment">//创建一个Runnable接口的匿名类实例，并将它传给了Thread类的构造方法</span></span><br><span class="line"> <span class="meta">@Override</span></span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span>&#123;</span><br><span class="line">     System.out.println(<span class="string">&quot;Thread is running&quot;</span>);</span><br><span class="line"> &#125;</span><br><span class="line">&#125;).start();  <span class="comment">//最后调用Thread类的 start() 方法执行这个线程</span></span><br><span class="line"><span class="comment">//这里使用匿名类的写法</span></span><br></pre></td></tr></table></figure>

<p>Kotlin 版本：</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">Thread(<span class="keyword">object</span>: Runnable&#123; <span class="comment">//创建匿名类实例改用 object关键字</span></span><br><span class="line">	<span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">run</span><span class="params">()</span></span>&#123;</span><br><span class="line">  println(<span class="string">&quot;Thread is running&quot;</span>)   </span><br><span class="line"> &#125;</span><br><span class="line">&#125;).start()</span><br><span class="line"></span><br><span class="line"><span class="comment">//简化版1： 因为只有一个待实现的方法</span></span><br><span class="line">Thread(Runnable&#123;</span><br><span class="line">  println(<span class="string">&quot;Thread is running&quot;</span>)   </span><br><span class="line">&#125;).start()</span><br><span class="line"></span><br><span class="line"><span class="comment">//简化版2：接口名省略（当java方法的参数列表只有一个Java单抽象方法接口参数时）</span></span><br><span class="line">Thread(&#123;</span><br><span class="line">  println(<span class="string">&quot;Thread is running&quot;</span>)   </span><br><span class="line">&#125;).start()</span><br><span class="line"></span><br><span class="line"><span class="comment">//简化版3： lambda 的优化</span></span><br><span class="line">Thread&#123;</span><br><span class="line">  println(<span class="string">&quot;Thread is running&quot;</span>)   </span><br><span class="line">&#125;.start()</span><br></pre></td></tr></table></figure>


</blockquote>
<h3 id="3-应用"><a href="#3-应用" class="headerlink" title="3. 应用"></a>3. 应用</h3><p><code>Kotlin</code> 调用 <code>SDK</code>接口时可能会用到： </p>
<p>如 <strong>点击事件接口</strong>  <code>OnClickListener</code></p>
<p>其定义：<code>public interface OnClickListener&#123; void onClick(View v);&#125;</code></p>
<p>若使用它：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// java 式书写</span></span><br><span class="line">button.setOnClickListener(<span class="keyword">new</span> <span class="title class_">View</span>.OnClickListener()&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">onClick</span><span class="params">(View v)</span>&#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>而<code>kotlin</code> 写：</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">button.setOnClickListener&#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://jonhsean.gitee.io/blog">Joey</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://jonhsean.gitee.io/blog/2022/10/14/daily/kotlin_lambda%E7%BC%96%E7%A8%8B/">https://jonhsean.gitee.io/blog/2022/10/14/daily/kotlin_lambda%E7%BC%96%E7%A8%8B/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://jonhsean.gitee.io/blog" target="_blank">Hexo</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/kotlin%E5%9F%BA%E7%A1%80/">kotlin基础</a><a class="post-meta__tags" href="/blog/tags/Java%E5%87%BD%E6%95%B0%E5%BC%8FAPI/">Java函数式API</a><a class="post-meta__tags" href="/blog/tags/kotlin%E9%9B%86%E5%90%88/">kotlin集合</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://unpkg.com/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://unpkg.com/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2022/10/14/daily/kotlin_classSPEC/"><img class="prev-cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">面向对象3:数据类和单例类-kotlin基础(三)</div></div></a></div><div class="next-post pull-right"><a href="/blog/2022/10/14/daily/kotlin_%E7%A9%BA%E6%8C%87%E9%92%88%E6%A3%80%E6%9F%A5/"><img class="next-cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">空指针检查-kotlin基础(五)</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2022/10/14/daily/kotlin_base/" title="变量和函数-kotlin基础(二)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">变量和函数-kotlin基础(二)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_classSPEC/" title="面向对象3:数据类和单例类-kotlin基础(三)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">面向对象3:数据类和单例类-kotlin基础(三)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_info/" title="介绍-kotlin基础(一)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">介绍-kotlin基础(一)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_interface/" title="面向对象2:接口-kotlin基础(三)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">面向对象2:接口-kotlin基础(三)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_oop/" title="面向对象1-kotlin基础(三)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">面向对象1-kotlin基础(三)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_%E5%B0%8F%E9%AD%94%E6%9C%AF/" title="小技巧-kotlin基础(六)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">小技巧-kotlin基础(六)</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Lambda%E7%BC%96%E7%A8%8B"><span class="toc-text">Lambda编程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E9%9B%86%E5%90%88%E7%9A%84%E5%88%9B%E5%BB%BA%EF%BC%8C%E9%81%8D%E5%8E%86"><span class="toc-text">一、集合的创建，遍历</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-List"><span class="toc-text">1. List</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-Set"><span class="toc-text">2. Set</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-Map-%E9%94%AE%E5%80%BC%E5%AF%B9%E5%BD%A2%E5%BC%8F"><span class="toc-text">3. Map 键值对形式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E6%93%8D%E4%BD%9C%E6%96%B9%E5%BC%8F"><span class="toc-text">1. 操作方式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E5%88%9B%E5%BB%BA%E5%B9%B6%E4%BD%BF%E7%94%A8"><span class="toc-text">2. 创建并使用</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E9%9B%86%E5%90%88%E7%9A%84%E5%87%BD%E6%95%B0%E5%BC%8FAPI"><span class="toc-text">二、集合的函数式API</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%BC%95%E5%AD%90"><span class="toc-text">1. 引子</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%AE%80%E5%86%99%E8%BF%9B%E5%8C%96%E5%8F%B2%EF%BC%9A"><span class="toc-text">简写进化史：</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-Lambda"><span class="toc-text">2. Lambda</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%89%B9%E7%82%B9%EF%BC%9A"><span class="toc-text">特点：</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%B8%B8%E7%94%A84%E4%B8%AAapi"><span class="toc-text">3. 常用4个api</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%89%E3%80%81Java%E5%87%BD%E6%95%B0%E5%BC%8FAPI%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">三、Java函数式API的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-text">1.是什么</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E6%80%8E%E4%B9%88%E7%94%A8"><span class="toc-text">2.怎么用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E5%BA%94%E7%94%A8"><span class="toc-text">3. 应用</span></a></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 By Joey</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="/blog/js/tw_cn.js"></script><script src="https://unpkg.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://unpkg.com/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/blog/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://unpkg.com/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://unpkg.com/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://unpkg.com/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="true"></script><script src="https://unpkg.com/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"]):not([href="/music/"]):not([href="/no-pjax/"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>